﻿namespace QiangPiao
{
    using SQ.Base;
    using System;
    using System.ComponentModel;
    using System.Drawing;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Windows.Forms;

    public class FrmLogin : Form
    {
        private Button btnLogin;
        private IContainer components = null;
        private FrmMain frmMain;
        public bool IsClosed = false;
        public bool IsRun = false;
        private Label label1;
        private Label label2;
        private Label lblUserName;
        private object m_lock = new object();
        private PictureBox picCheckCode;
        private TextBox txtCheckCode;
        private TextBox txtPassWord;
        private TextBox txtUserName;

        public FrmLogin(FrmMain frmMain)
        {
            this.InitializeComponent();
            this.frmMain = frmMain;
            this.RefreshCheckCode();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                this.btnLogin.Enabled = false;
                Thread thread = new Thread(new ThreadStart(this.RunLogin))
                {
                    IsBackground = true
                };
                this.IsRun = true;
                thread.Start();
            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Log.WriteLog4Ex("btnLogin_Click", exception);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if(disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void FrmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.IsClosed = true;
            this.IsRun = false;
        }

        private void InitializeComponent()
        {
            this.lblUserName = new Label();
            this.txtUserName = new TextBox();
            this.label1 = new Label();
            this.txtPassWord = new TextBox();
            this.label2 = new Label();
            this.txtCheckCode = new TextBox();
            this.picCheckCode = new PictureBox();
            this.btnLogin = new Button();
            ((ISupportInitialize)this.picCheckCode).BeginInit();
            base.SuspendLayout();
            this.lblUserName.Anchor = AnchorStyles.None;
            this.lblUserName.AutoSize = true;
            this.lblUserName.Location = new Point(0x2c, 0x21);
            this.lblUserName.Name = "lblUserName";
            this.lblUserName.Size = new Size(0x2f, 12);
            this.lblUserName.TabIndex = 0;
            this.lblUserName.Text = "用户名:";
            this.txtUserName.Anchor = AnchorStyles.None;
            this.txtUserName.Location = new Point(0x61, 30);
            this.txtUserName.Name = "txtUserName";
            this.txtUserName.Size = new Size(0x94, 0x15);
            this.txtUserName.TabIndex = 1;
            this.label1.Anchor = AnchorStyles.None;
            this.label1.AutoSize = true;
            this.label1.Location = new Point(0x2c, 60);
            this.label1.Name = "label1";
            this.label1.Size = new Size(0x23, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "密码:";
            this.txtPassWord.Anchor = AnchorStyles.None;
            this.txtPassWord.Location = new Point(0x61, 0x39);
            this.txtPassWord.Name = "txtPassWord";
            this.txtPassWord.PasswordChar = '*';
            this.txtPassWord.Size = new Size(0x94, 0x15);
            this.txtPassWord.TabIndex = 2;
            this.label2.Anchor = AnchorStyles.None;
            this.label2.AutoSize = true;
            this.label2.Location = new Point(0x2c, 0x57);
            this.label2.Name = "label2";
            this.label2.Size = new Size(0x2f, 12);
            this.label2.TabIndex = 0;
            this.label2.Text = "验证码:";
            this.txtCheckCode.Anchor = AnchorStyles.None;
            this.txtCheckCode.Location = new Point(0x61, 0x54);
            this.txtCheckCode.Name = "txtCheckCode";
            this.txtCheckCode.Size = new Size(0x3e, 0x15);
            this.txtCheckCode.TabIndex = 3;
            this.picCheckCode.Anchor = AnchorStyles.None;
            this.picCheckCode.Cursor = Cursors.Hand;
            this.picCheckCode.Location = new Point(0xa5, 0x54);
            this.picCheckCode.Name = "picCheckCode";
            this.picCheckCode.Size = new Size(0x4e, 0x1a);
            this.picCheckCode.TabIndex = 2;
            this.picCheckCode.TabStop = false;
            this.picCheckCode.Click += new EventHandler(this.picCheckCode_Click);
            this.btnLogin.Anchor = AnchorStyles.None;
            this.btnLogin.Location = new Point(170, 0x74);
            this.btnLogin.Name = "btnLogin";
            this.btnLogin.Size = new Size(0x4b, 0x17);
            this.btnLogin.TabIndex = 4;
            this.btnLogin.Text = "登录";
            this.btnLogin.UseVisualStyleBackColor = true;
            this.btnLogin.Click += new EventHandler(this.btnLogin_Click);
            base.AcceptButton = this.btnLogin;
            base.AutoScaleDimensions = new SizeF(6f, 12f);
            //base.AutoScaleMode = AutoScaleMode.Font;
            base.ClientSize = new Size(0x120, 0xa6);
            base.Controls.Add(this.btnLogin);
            base.Controls.Add(this.picCheckCode);
            base.Controls.Add(this.txtCheckCode);
            base.Controls.Add(this.label2);
            base.Controls.Add(this.txtPassWord);
            base.Controls.Add(this.label1);
            base.Controls.Add(this.txtUserName);
            base.Controls.Add(this.lblUserName);
            base.Name = "FrmLogin";
            base.StartPosition = FormStartPosition.CenterScreen;
            this.Text = "登录";
            base.FormClosing += new FormClosingEventHandler(this.FrmLogin_FormClosing);
            ((ISupportInitialize)this.picCheckCode).EndInit();
            base.ResumeLayout(false);
            base.PerformLayout();
        }

        private bool Login()
        {
            MethodInvoker method = null;
            try
            {
                string str = this.frmMain.http.PostPage(string.Format("https://dynamic.12306.cn/otsweb/loginAction.do?method=login&loginUser.user_name={0}&nameErrorFocus=&passwordErrorFocus=&randCode={2}&randErrorFocus=focus&user.password={1}", this.txtUserName.Text, this.txtPassWord.Text, this.txtCheckCode.Text), "", Encoding.UTF8, "text/html");
                this.frmMain.WriteHtml(str);
                if(this.frmMain.rexLogin.Match(str).Success)
                {
                    this.frmMain.WriteInfo("登录成功!");
                    this.frmMain.WriteInfo("Cookie:dynamic.12306.cn/otsweb/\r\n" + this.frmMain.http.GetCookieStr(new Uri("https://dynamic.12306.cn/otsweb/")));
                    if(method == null)
                    {
                        method = delegate
                        {
                            lock(this.m_lock)
                            {
                               // MessageBox.Show("登录成功!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                base.Close();
                                this.frmMain.IsLogin = true;
                                this.frmMain.NavigateMain();
                            }
                        };
                    }
                    base.BeginInvoke(method);
                }
                else if(str.Contains("系统维护中【维护时间：01:30-06:00】，请稍候访问，谢谢！"))
                {
                    this.frmMain.WriteInfo("系统维护中【维护时间：01:30-06:00】，请稍候访问，谢谢！");
                }
                else
                {
                    Match match = this.frmMain.rexEx2.Match(str);
                    if(!match.Success)
                    {
                        match = this.frmMain.rexEx.Match(str);
                    }
                    if(match.Success)
                    {
                        if(match.Groups[1].Value.Contains("当前访问用户过"))
                        {
                            this.frmMain.WriteInfo(match.Groups[1].Value);
                            return true;
                        }
                        this.frmMain.WriteInfo(match.Groups[1].Value + "登录已中止！");
                    }
                    else
                    {
                        this.frmMain.WriteInfo("未知错误，登录已中止！");
                    }
                }
            }
            catch(Exception exception)
            {
                this.frmMain.WriteInfo("发送错误，登录已中止!错误详细信息：" + exception.Message);
                Log.WriteLog4Ex("Login", exception);
            }
            return false;
        }

        private void picCheckCode_Click(object sender, EventArgs e)
        {
            this.RefreshCheckCode();
        }

        private void RefreshCheckCode()
        {
            try
            {
                this.picCheckCode.Image = this.frmMain.http.Getimg("https://dynamic.12306.cn/otsweb/passCodeAction.do?rand=lrand&" + new Random().NextDouble(), "image/png,image/*;q=0.8,*/*;q=0.5");
            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Log.WriteLog4Ex("RefreshCheckCode", exception);
            }
        }

        private void RunLogin()
        {
            MethodInvoker method = null;
            try
            {
                this.frmMain.ChangeState("登录中");
                while(this.IsRun && this.Login())
                {
                    Thread.Sleep(0x3e8);
                }
            }
            catch(Exception exception)
            {
                this.frmMain.WriteInfo("发送错误，错误详细信息：" + exception.Message);
                Log.WriteLog4Ex("RunLogin", exception);
            }
            finally
            {
                lock(this.m_lock)
                {
                    if(!this.IsClosed)
                    {
                        if(method == null)
                        {
                            method = delegate
                            {
                                this.btnLogin.Enabled = true;
                                if(!this.frmMain.IsLogin)
                                {
                                    MessageBox.Show("自动登录已停止，如未登录成功，请手动重试！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                }
                            };
                        }
                        base.BeginInvoke(method);
                    }
                }
                this.frmMain.ChangeState("待命");
            }
        }
    }
}

